<template>
  <div class="page">
    <!-- 搜索区域 开始 -->
    <div class="el_card_box">
      <el-form :inline="true" size="small" :model="formInline" class="search_form">
        <el-form-item label="预约时间：">
          <el-date-picker v-model="formInline.orderTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="创建预约时间：">
          <el-date-picker v-model="formInline.createTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="客户报名时间：">
          <el-date-picker v-model="formInline.applyTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="收款时间：">
          <el-date-picker v-model="formInline.followTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="负责人：">
          <el-select v-model="formInline.principal" filterable clearable>
            <el-option v-for="(item,index) in userList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="广告来源：">
          <el-select v-model="formInline.channelSource" filterable clearable @change="getAdCodeList">
            <el-option v-for="(item,index) in sourceList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="广告代号：">
          <el-select v-model="formInline.adSource" filterable clearable>
            <el-option v-for="(item,index) in adCodeList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门：">
          <depart-ment v-model="formInline.departmentId"></depart-ment>
        </el-form-item>

      </el-form>
      <div class="search_btn_box">
        <el-button type="primary" size="small" @click="onSearch">筛选</el-button>
        <el-button type="default" size="small" @click="rest">清空筛选</el-button>
      </div>
    </div>
    <!-- 搜索区域 end -->

    <!-- 表格 开始 -->
    <div class="table_box">
      <!-- 操作区域 开始 -->
      <div class="action_box">
        <!-- <el-button type="primary" size="small" :loading="eloading" @click="downloadExcel">导出筛选结果</el-button> -->
        <auth-button uid="1070201" type="primary" size="small" :loading="eloading" @click.native="downloadExcel">导出筛选结果</auth-button>
      </div>
      <!-- 操作区域 end -->

      <el-table ref="elTable" class="el_table" size="small" show-summary :summary-method="getSummaries" :data="tableData">
        <el-table-column prop="principal" label="负责人" show-overflow-tooltip />
        <el-table-column prop="newCustomerCnt" label="新增客户数" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.newCustomerCnt||0 }}</template>
        </el-table-column>
        <el-table-column prop="newAppointmentCnt" label="总预约数" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.newAppointmentCnt||0 }}</template>
        </el-table-column>
        <el-table-column prop="appointmentCnt" label="到期预约数" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.appointmentCnt||0 }}</template>
        </el-table-column>
        <el-table-column prop="arrivedCnt" label="到店人数" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.arrivedCnt||0 }}</template>
        </el-table-column>
        <el-table-column prop="arrivedDealCnt" label="成交人数" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.arrivedDealCnt||0 }}</template>
        </el-table-column>
        <el-table-column prop="dealAmount" label="成交金额" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.dealAmount||0 }}</template>
        </el-table-column>
        <el-table-column prop="collectMoney" label="收款金额" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.collectMoney?Number(row.collectMoney.toFixed(0)):row.collectMoney }}</template>
        </el-table-column>
        <el-table-column prop="appointmentArrivedRate" label="预约到店率" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.appointmentArrivedRate?row.appointmentArrivedRate.toFixed(0):0 }}%</template>
        </el-table-column>
        <el-table-column prop="arrivedDealRate" label="到店成交率" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.arrivedDealRate?row.arrivedDealRate.toFixed(0):0 }}%</template>
        </el-table-column>
        <el-table-column prop="averageCustomerUnitPrice" label="平均客单价" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.averageCustomerUnitPrice?row.averageCustomerUnitPrice.toFixed(0):0 }}</template>
        </el-table-column>
        <el-table-column prop="mainDemandsCnt" label="矫正/种植成交人数" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.mainDemandsCnt||0 }}</template>
        </el-table-column>
        <el-table-column prop="mainDemandsArrivedRate" label="矫正/种植到店成交率" show-overflow-tooltip>
          <template slot-scope="{row}">{{ row.mainDemandsArrivedRate?row.mainDemandsArrivedRate.toFixed(0):0 }}%</template>
        </el-table-column>

      </el-table>
      <div class="pagination_list">
        <el-pagination background layout="sizes, total,prev, pager, next, jumper" :total="pageTotal" :page-size="pageSize" :page-sizes="pageSizes" :current-page.sync="pageNumber" @current-change="getList" @size-change="changePageSize" />
      </div>
    </div>
    <!-- 表格 end -->

  </div>
</template>

<script>
import {
  GETORDERSEARCHSTAT,
  ORDEREXPORTSTAT
} from '@/http/info'
import {
  GETADSOURCEOPTIONS,
  GETCHANNELSOURCEOPTIONS,
  GETUSEROPTIONS
} from '@/http/system'
import { showToast, showModal, deepClone } from '@/common/util'
import { exportExcel } from '@/common/common'
import AuthButton from '@/components/auth-button'
import moment from 'moment'
export default {
  name: 'BookPage',
  components: {
    AuthButton
  },
  props: {
    status: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      formInline: {},
      tableData: [],
      pageTotal: 0,
      pageNumber: 1,
      pageSizes: [10, 20, 50, 100],
      pageSize: 20,
      orderTime: [],
      orderTime2: [],
      showDialog: false,
      loading: false,
      eloading: false,
      adCodeList: [],
      userList: [],
      sourceList: [],
      summary:{}
    }
  },
  created(){
    let n = moment().format('YYYY-MM-DD')
    let min = moment(new Date()).subtract(3, 'months').format('YYYY-MM-DD')
    this.$set(this.formInline,'orderTime',[min,n])
  },
  mounted() {
    this.getList()
    this.getSource()
    this.getUser()
    this.getAdCodeList()
  },
  methods: {
    /** 重置 */
    rest() {
      this.formInline = {}
      this.getList()
      this.getAdCodeList()
    },

    /** 每页展示 */
    changePageSize(e) {
      this.pageSize = e
      this.getList()
    },

    /** 获取参数 */
    getParams() {
      const oParams = deepClone(this.formInline)

      if (oParams.orderTime && oParams.orderTime.length > 0) {
        oParams.orderStartTime = oParams.orderTime[0]
        oParams.orderEndTime = oParams.orderTime[1]
      } else {
        delete oParams.orderStartTime
        delete oParams.orderEndTime
      }

      if (oParams.createTime && oParams.createTime.length > 0) {
        oParams.orderCreateStartTime = oParams.createTime[0]
        oParams.orderCreateEndTime = oParams.createTime[1]
      } else {
        delete oParams.orderCreateStartTime
        delete oParams.orderCreateEndTime
      }

      if (oParams.applyTime && oParams.applyTime.length > 0) {
        oParams.enrollStartTime = oParams.applyTime[0]
        oParams.enrollEndTime = oParams.applyTime[1]
      } else {
        delete oParams.enrollStartTime
        delete oParams.enrollEndTime
      }

      if (oParams.followTime && oParams.followTime.length > 0) {
        oParams.collectStartTime = oParams.followTime[0];
        oParams.collectEndTime = oParams.followTime[1];
      } else {
        delete oParams.collectStartTime;
        delete oParams.collectEndTime;
      }

      delete oParams.orderTime
      delete oParams.createTime
      delete oParams.applyTime
      delete oParams.followTime

      oParams.pageNumber = this.pageNumber
      oParams.pageSize = this.pageSize
      return oParams
    },

    /** 获取列表 */
    getList() {
      const _this = this
      const oParams = this.getParams()
      GETORDERSEARCHSTAT(oParams).then((res) => {
        const obj = res.data || {}
        _this.tableData = obj.list || []
        _this.pageTotal = obj.totalElements
        _this.summary = res.summary
      })
    },

    // 导出excel
    downloadExcel() {
      const _this = this
      const o = deepClone(_this.formInline)
      const m = Object.keys(o)
      if (m.length > 0) {
        showModal({
          message: '确定是否导出筛选条件下面所有销售统计列表?',
          showCancelButton: true,
          type: 'warning',
          success: function() {
            _this.dowloadExcelFile()
          }
        })
        return false
      }
      showToast({
        message: '请选择筛选条件后再导出'
      })
    },

    // 下载excel
    dowloadExcelFile() {
      const _this = this
      const oParams = this.getParams()
      const options = {}
      options.method = 'GET'
      options.data = oParams
      options.url = ORDEREXPORTSTAT
      options.fileName = '销售统计列表.xlsx'
      _this.eloading = true
      exportExcel(options).then((res) => {
        _this.eloading = false
      })
    },

    // 获取负责人列表
    getUser(name) {
      GETUSEROPTIONS({ username: name }).then((res) => {
        this.userList = res.data || []
      })
    },

    // 获取所有广告来源
    getSource() {
      GETCHANNELSOURCEOPTIONS().then((res) => {
        this.sourceList = res.data || []
      })
    },

    // 获取广告代号
    getAdCodeList(id) {
      if (this.formInline.adSource) {
        delete this.formInline.adSource
      }
      GETADSOURCEOPTIONS({ csId: id }).then((res) => {
        this.adCodeList = res.data || []
      })
    },

    // 自定义展示合计
    getSummaries(param) {
      const { columns, data } = param;
      let summary = this.summary;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }

        if(column.property == 'appointmentArrivedRate'){
          sums[index] = (summary[column.property]?(summary[column.property]*100).toFixed(0):0) + '%';
          return
        }

        if(column.property == 'averageCustomerUnitPrice'){
          sums[index] = summary[column.property]?summary[column.property].toFixed(0):0;
          return
        }

        if(column.property == 'mainDemandsArrivedRate'){
          sums[index] = (summary[column.property]?(summary[column.property]*100).toFixed(0):0) + '%';
          return
        }
        sums[index] = summary[column.property];
      });
      return sums;
    },

    // 搜索
    onSearch(){
      this.pageNumber = 1;
      this.getList()
    }

  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/style/customer/index.scss";
</style>
